<?php

namespace stlswm\KhyTms\QueryOrders;

use Exception;
use GuzzleHttp\Exception\GuzzleException;
use stlswm\JsonObject\Json;
use stlswm\KhyTms\Client;

/**
 * Class Request
 *
 * @package stlswm\KhyTms\QueryOrders
 */
class Request extends \stlswm\KhyTms\Request
{
    public $page;//页码，1开始
    public $size;//单页最大订单数
    public $state;//订单状态，0已撤销，1已下单，2已接单，3已装货，4已签收，1000待处理，无法查看全部状态，不传则默认0已撤销
    public $timeType;//查询时间类型，created录入时间，deliveryed提货时间，appointArrived预约提货时间，signed签收时间
    public $startDate;//起始时间，格式"yyyy-MM-dd HH:mm:ss"
    public $endDate;//结束时间，格式"yyyy-MM-dd HH:mm:ss"
    public $orderNumber;//TMS运单号
    public $customerOrderNumber;//客户单号
    public $packNumber;//车次号
    public $consignerName;//发货人姓名，模糊搜索
    public $consignerPhone;//发货人电话，模糊搜索
    public $consigneeName;//收货人姓名，模糊搜索
    public $consigneePhone;//收货人电话，模糊搜索
    public $driverName;//司机姓名，模糊搜索
    public $driverPhone;//司机电话，模糊搜索
    public $carNumber;//司机车牌号码，模糊搜索

    public function jsonFormat(): string
    {
        $data = [
            'page' => $this->page,
            'size' => $this->size,
        ];
        $properties = [
            'state',
            'timeType',
            'startDate',
            'endDate',
            'orderNumber',
            'customerOrderNumber',
            'packNumber',
            'consignerName',
            'consignerPhone',
            'consigneeName',
            'consigneePhone',
            'driverName',
            'driverPhone',
            'carNumber',
        ];
        foreach ($properties as $property) {
            if ($this->$property !== null) {
                $data[$property] = $this->$property;
            }
        }
        return json_encode($data);
    }

    /**
     * @param Client $client
     *
     * @return Response
     * @throws GuzzleException
     * @throws Exception
     */
    public function jsonReq(Client $client): Response
    {
        $apiRes = $client->jsonReq('/order/query_orders', $this);
        $response = new Response();
        $bool = Json::unMarshal($apiRes, $response);
        if (!$bool) {
            throw new Exception('无法解析返回：' . $apiRes);
        }
        return $response;
    }
}